package com.qtfreet.musicuu.ui.service;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.qtfreet.musicuu.R;
import com.qtfreet.musicuu.model.Constant.Constants;
import com.qtfreet.musicuu.musicApi.MusicBean.eventbus.EventCtrBean;
import com.qtfreet.musicuu.musicApi.MusicBean.eventbus.EventInitBean;
import com.qtfreet.musicuu.musicApi.MusicBean.eventbus.MediaPlayerEventBean;
import com.qtfreet.musicuu.ui.activity.MainActivity;
import com.qtfreet.musicuu.ui.activity.PlayMusicActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by qtfreet on 2016/3/23.
 * 播放service
 */
public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnErrorListener {

    private MediaPlayer mediaPlayer;

    // 更新SeekBar进度的定时器
    private Timer timer;

    public MusicService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        EventBus.getDefault().register(this);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnBufferingUpdateListener(this);
        mediaPlayer.setOnErrorListener(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (mediaPlayer != null) {
            mediaPlayer.reset();
            mediaPlayer.release();
        }
    }

    //事件接收处
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventMsgCtrl(String msg) {
        if (msg.equals(PlayMusicActivity.PAUSE_TO_PREPARE)) {
            pauseToPrepare();
        }
        if (msg.equals(PlayMusicActivity.STOP_NOW)) {
            stop();
        }
        if (msg.equals(PlayMusicActivity.PAUSE_NOW)) {
            pause();
        }
        if (msg.equals(PlayMusicActivity.START_NOW)) {
            start();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventMsgCtrl(EventCtrBean msg) {
        if (msg.msg.equals(PlayMusicActivity.SEEK)) {
            mediaPlayer.seekTo(msg.seek);
        }
        if (msg.msg.equals(PlayMusicActivity.SEEK_TO)) {
            if (mediaPlayer != null) {
                mediaPlayer.seekTo(msg.seek);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventMsgCtrl(EventInitBean msg) {
        init(msg.url, msg.isError);
    }

    private String tempUrl = "";

    public void init(String url, boolean isError) {
        try {
            if (!tempUrl.equals(url)) {
                mediaPlayer.reset();
                //     MediaSource mediaSource = new UriSource(PlayMusicActivity.this, Uri.parse(song_urls[position]));
                mediaPlayer.setDataSource(url);
                tempUrl = url;
                if (isError) {
                    mediaPlayer.prepare();
                } else {
                    mediaPlayer.prepareAsync();
                }
            } else {
                EventBus.getDefault().postSticky(new MediaPlayerEventBean(TYPE_ON_PREPARED, mediaPlayer, true));
                Log.d("flag", "这里运行了  1111111111    ");
            }
        } catch (Exception e) {
            Toast.makeText(MusicService.this, "歌曲播放失败", Toast.LENGTH_SHORT).show();

        }

    }

    /**
     * 停止
     */
    private void stop() {
        if (null != mediaPlayer) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    /**
     * 暂停
     */
    private void pause() {
        if (mediaPlayer != null) {
            mediaPlayer.pause();
        }
    }

    /**
     * 开始
     */
    public static final String TYPE_ONTIME_PROGRESS = "getCurrentPosition";

    private void start() {
        if (mediaPlayer != null) {
            mediaPlayer.start();
        }
        // 音乐开始播放后，控制SeekBar进度
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // 每隔一段时间，发送一次广播。主界面不断接收广播后，执行SeekBar进度更新的操作
                EventBus.getDefault().postSticky(new MediaPlayerEventBean(TYPE_ONTIME_PROGRESS, mediaPlayer));
            }
        }, 0, 1000);
    }

    private void pauseToPrepare() {
        if (null != mediaPlayer) {
            mediaPlayer.reset();
        }
    }

    public static final String TYPE_ON_PREPARED = "onPrepared";

    @Override
    public void onPrepared(MediaPlayer mp) {
        EventBus.getDefault().postSticky(new MediaPlayerEventBean(TYPE_ON_PREPARED, mp, false));
    }

    public static final String TYPE_ON_COMPLETION = "onCompletion";

    @Override
    public void onCompletion(MediaPlayer mp) {
        EventBus.getDefault().postSticky(new MediaPlayerEventBean(TYPE_ON_COMPLETION, mp));
    }

    public static final String TYPE_ON_BUFFERING_UPDATE = "onBufferingUpdate";

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        EventBus.getDefault().postSticky(new MediaPlayerEventBean(TYPE_ON_BUFFERING_UPDATE, mp, percent));
    }

    public static final String TYPE_ON_ERROR = "onError";

    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        EventBus.getDefault().postSticky(new MediaPlayerEventBean(TYPE_ON_ERROR, mp, what, extra));
        return false;
    }
}
